package com.zgs.mall.auth.classload;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class MyClassLoad  extends  ClassLoader{
    private String classPath;

    public MyClassLoad(String classPath){
        this.classPath=classPath;
    }

    protected byte[] loadByte(String name) throws Exception {
        name = name.replaceAll("\\.", "/");
        FileInputStream fis = new FileInputStream(classPath + "/" + name  + ".class");
        int len = fis.available();
        byte[] data = new byte[len];
         fis.read(data);
         fis.close();
         return data;
    }
    //URLClassLoad
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] data = loadByte(name);
            //src="/item/将一个字节数组转为Class对象，这个字节数组是class文件读取后最终的字节 数组。

        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ClassNotFoundException();
    }
    //打破双亲委派机制
    protected Class<?> loadClass(String name, boolean resolve)
            throws ClassNotFoundException
    {
        synchronized (getClassLoadingLock(name)) {
            // First, check if the class has already been loaded
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                if (name.startsWith("com.meima")){
                    c = findClass(name);
                }else{
                    //java基础类只能用bootstartClassLoad
                    c = this.getParent().loadClass(name);
                }

            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }

    public static void main(String[] args) throws Exception {
        MyClassLoad myClassLoad = new MyClassLoad("E:\\logs");

            Class<?> clazz = myClassLoad.loadClass("com.meima.app.goods.vo.PddGoodsPromotion",false);
        System.out.println(clazz.getClassLoader());
    }
}
